//
//  TuiHuoPictureTableViewCell.m
//  Experss
//
//  Created by wmwMAC on 17/8/9.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "TuiHuoPictureTableViewCell.h"

#import "TuiHuoTableCollectionViewCell.h"

@interface TuiHuoPictureTableViewCell ()<UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TuiHuoPictureTableCollectionCellDelegate>
{

    UIImagePickerController *_imagePickerController;// 相机
    UIImage *imageF;
    NSData *temp64;//用于图片上传
    
    UIButton *deletBtn;
}

@property (nonatomic , strong) UICollectionView *collectionView;


@end

@implementation TuiHuoPictureTableViewCell


-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self createPictureCollectionView];

    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
}
-(void)createPictureCollectionView{
    
    CGFloat itemS = (kScreenWidth-5*20)/4;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 定义大小
    layout.itemSize = CGSizeMake(itemS, itemS);
    // 设置最小行间距
    layout.minimumLineSpacing = 20;
    // 设置垂直间距
    layout.minimumInteritemSpacing = 0;
    // 设置滚动方向（默认垂直滚动)
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(20, 10, kScreen_Width-40, itemS + 20) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.bounces = NO;
    _collectionView.scrollEnabled = NO;
    [_collectionView registerClass:[TuiHuoTableCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    self.collectionView = _collectionView;
    [self.contentView addSubview:_collectionView];
    
    UILabel *footLable = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(_collectionView.frame), kScreenWidth-40, 15)];
    footLable.text = @"没张图片不超过5M,支持jpg格式,最多上传3张";
    footLable.textColor = [UIColor lightGrayColor];
    footLable.font = [UIFont systemFontOfSize:12];
    [self.contentView addSubview:footLable];
    
    _imageArray = [NSMutableArray array];
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
   
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (self.imageArray.count < 3 && self.imageArray.count > 0) {
         return self.imageArray.count+1;
    }else if (self.imageArray.count == 0){
        return 1;
    }else{
        return self.imageArray.count;
    }
   
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TuiHuoTableCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.imgV.backgroundColor = [UIColor cyanColor];
    
    
    if (indexPath.item < self.imageArray.count) {
        cell.imgV.image = self.imageArray[indexPath.item];
//        cell.deletBtn.hidden = NO;
        //    [cell.imgV sd_setImageWithURL:[NSURL URLWithString:self.imageArray[indexPath.item]]];
//        cell.tag = indexPath.row + 2000;
        
        
        deletBtn = [BasePublicCreatUI createBtnFrame:CGRectMake(cell.frame.size.width*(indexPath.item+1) +indexPath.item*20 - 10, 0, 20, 20) title:nil bgImage:nil selectBgImage:nil image:@"shenqingtuihuo_jian" target:self action:@selector(deletCellImg:)];
        deletBtn.tag = indexPath.item+3000;
        [self.collectionView addSubview:deletBtn];
        
        
        
    }else{
        cell.imgV.image = [UIImage imageNamed:@"shenqingtuihuo_tianjiatupian"];
    }
    
    
    return cell;
}
-(void)deletCellImg:(UIButton *)sender{
    for (NSInteger i = 0; i<_imageArray.count; i++) {
        deletBtn = [self.collectionView viewWithTag:i+3000];
        [deletBtn removeFromSuperview];
    }
    [_imageArray removeObjectAtIndex:sender.tag-3000];
    
    NSDictionary *dict = @{@"imageAray":self.imageArray};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"putImageArrayAction" object:nil userInfo:dict];
    
    [self.collectionView reloadData];
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%ld",indexPath.row);
    if (indexPath.row == _imageArray.count) {
        //调用相机
        
        [self selectImageBtnClick];
    }
}


#pragma mark ---------------------------    调用相机   -------------------
-(void)selectImageBtnClick {
    UIViewController *currentVC = [BasePublicClass getCurrentVC];
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        
    }];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"打开相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        [currentVC presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *picture = [UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = NO;
        
        [currentVC presentViewController:pickerImage animated:YES completion:nil];
    }];
    [alertVc addAction:cancle];
    [alertVc addAction:camera];
    [alertVc addAction:picture];
    [currentVC presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark UIImagePickerControllerDelegate
//该代理方法仅适用于只选取图片时
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    
    imageF = image;
    
    //压缩图片
    NSData *fileData = UIImageJPEGRepresentation(image, 1.0);
    temp64  = [fileData base64EncodedDataWithOptions:(0)];
  
    //上传图片 temp64
    for (NSInteger i = 0; i<_imageArray.count; i++) {
        deletBtn = [self.collectionView viewWithTag:i+3000];
        [deletBtn removeFromSuperview];
    }
    [self.imageArray addObject:image];
    NSLog(@"----%@",self.imageArray);
    [self.collectionView reloadData];
    UIViewController *currentVC = [BasePublicClass getCurrentVC];
    [currentVC dismissViewControllerAnimated:YES completion:nil];
    
    NSDictionary *dict = @{@"imageAray":self.imageArray};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"putImageArrayAction" object:nil userInfo:dict];
}



@end
